<template>
  <div class="monitor-log">
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 操作日志 -->
      <el-tab-pane label="操作日志" name="operation">
        <div class="log-header">
          <el-form :inline="true" :model="operationQuery" class="query-form">
            <el-form-item label="操作类型">
              <el-select v-model="operationQuery.type" placeholder="请选择操作类型" clearable>
                <el-option label="登录" value="login" />
                <el-option label="新增" value="create" />
                <el-option label="修改" value="update" />
                <el-option label="删除" value="delete" />
                <el-option label="导出" value="export" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
            <el-form-item label="操作人">
              <el-input v-model="operationQuery.operator" placeholder="请输入操作人" clearable />
            </el-form-item>
            <el-form-item label="操作时间">
              <el-date-picker
                v-model="operationQuery.timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQueryOperationLog">查询</el-button>
              <el-button @click="handleResetOperationQuery">重置</el-button>
              <el-button type="success" @click="handleExportOperationLog">导出</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table
          v-loading="operationLoading"
          :data="operationLogs"
          border
          style="width: 100%"
        >
          <el-table-column type="index" width="50" />
          <el-table-column prop="type" label="操作类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getOperationTypeTag(row.type)">
                {{ getOperationTypeLabel(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="operator" label="操作人" width="120" />
          <el-table-column prop="module" label="操作模块" width="120" />
          <el-table-column prop="content" label="操作内容" min-width="200" show-overflow-tooltip />
          <el-table-column prop="ip" label="IP地址" width="120" />
          <el-table-column prop="location" label="操作地点" width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                {{ row.status === 'success' ? '成功' : '失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="操作时间" width="160" />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleViewOperationDetail(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="operationQuery.pageNum"
            v-model:page-size="operationQuery.pageSize"
            :total="operationTotal"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleOperationSizeChange"
            @current-change="handleOperationCurrentChange"
          />
        </div>
      </el-tab-pane>

      <!-- 系统日志 -->
      <el-tab-pane label="系统日志" name="system">
        <div class="log-header">
          <el-form :inline="true" :model="systemQuery" class="query-form">
            <el-form-item label="日志级别">
              <el-select v-model="systemQuery.level" placeholder="请选择日志级别" clearable>
                <el-option label="INFO" value="info" />
                <el-option label="WARN" value="warn" />
                <el-option label="ERROR" value="error" />
                <el-option label="DEBUG" value="debug" />
              </el-select>
            </el-form-item>
            <el-form-item label="模块">
              <el-input v-model="systemQuery.module" placeholder="请输入模块名称" clearable />
            </el-form-item>
            <el-form-item label="日志时间">
              <el-date-picker
                v-model="systemQuery.timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuerySystemLog">查询</el-button>
              <el-button @click="handleResetSystemQuery">重置</el-button>
              <el-button type="success" @click="handleExportSystemLog">导出</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table
          v-loading="systemLoading"
          :data="systemLogs"
          border
          style="width: 100%"
        >
          <el-table-column type="index" width="50" />
          <el-table-column prop="level" label="日志级别" width="100">
            <template #default="{ row }">
              <el-tag :type="getLogLevelTag(row.level)">
                {{ row.level }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="module" label="模块" width="120" />
          <el-table-column prop="content" label="日志内容" min-width="200" show-overflow-tooltip />
          <el-table-column prop="stackTrace" label="堆栈信息" min-width="200" show-overflow-tooltip />
          <el-table-column prop="createTime" label="记录时间" width="160" />
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleViewSystemDetail(row)">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="systemQuery.pageNum"
            v-model:page-size="systemQuery.pageSize"
            :total="systemTotal"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSystemSizeChange"
            @current-change="handleSystemCurrentChange"
          />
        </div>
      </el-tab-pane>

      <!-- 安全日志 -->
      <el-tab-pane label="安全日志" name="security">
        <div class="log-header">
          <el-form :inline="true" :model="securityQuery" class="query-form">
            <el-form-item label="事件类型">
              <el-select v-model="securityQuery.type" placeholder="请选择事件类型" clearable>
                <el-option label="登录异常" value="login_error" />
                <el-option label="密码错误" value="password_error" />
                <el-option label="越权访问" value="unauthorized" />
                <el-option label="敏感操作" value="sensitive" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
            <el-form-item label="IP地址">
              <el-input v-model="securityQuery.ip" placeholder="请输入IP地址" clearable />
            </el-form-item>
            <el-form-item label="事件时间">
              <el-date-picker
                v-model="securityQuery.timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuerySecurityLog">查询</el-button>
              <el-button @click="handleResetSecurityQuery">重置</el-button>
              <el-button type="success" @click="handleExportSecurityLog">导出</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-table
          v-loading="securityLoading"
          :data="securityLogs"
          border
          style="width: 100%"
        >
          <el-table-column type="index" width="50" />
          <el-table-column prop="type" label="事件类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getSecurityTypeTag(row.type)">
                {{ getSecurityTypeLabel(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="ip" label="IP地址" width="120" />
          <el-table-column prop="location" label="地理位置" width="120" />
          <el-table-column prop="content" label="事件内容" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="处理状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getSecurityStatusTag(row.status)">
                {{ getSecurityStatusLabel(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="发生时间" width="160" />
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleViewSecurityDetail(row)">
                详情
              </el-button>
              <el-button
                v-if="row.status === 'pending'"
                type="success"
                link
                @click="handleProcessSecurityEvent(row)"
              >
                处理
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="securityQuery.pageNum"
            v-model:page-size="securityQuery.pageSize"
            :total="securityTotal"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSecuritySizeChange"
            @current-change="handleSecurityCurrentChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="detailDialogTitle"
      width="800px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <template v-for="(value, key) in currentDetail" :key="key">
          <el-descriptions-item :label="getDetailLabel(key)">
            {{ value }}
          </el-descriptions-item>
        </template>
      </el-descriptions>
    </el-dialog>

    <!-- 安全事件处理对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="处理安全事件"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理方式" prop="action">
          <el-select v-model="processForm.action">
            <el-option label="忽略" value="ignore" />
            <el-option label="封禁IP" value="block_ip" />
            <el-option label="锁定账号" value="lock_account" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理说明" prop="remark">
          <el-input
            v-model="processForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入处理说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitProcess">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getOperationLogs,
  getSystemLogs,
  getSecurityLogs,
  exportOperationLogs,
  exportSystemLogs,
  exportSecurityLogs,
  processSecurityEvent
} from '@/api/message'

// 当前激活的标签页
const activeTab = ref('operation')

// 操作日志相关
const operationLoading = ref(false)
const operationLogs = ref([])
const operationTotal = ref(0)
const operationQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  type: '',
  operator: '',
  timeRange: []
})

// 系统日志相关
const systemLoading = ref(false)
const systemLogs = ref([])
const systemTotal = ref(0)
const systemQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  level: '',
  module: '',
  timeRange: []
})

// 安全日志相关
const securityLoading = ref(false)
const securityLogs = ref([])
const securityTotal = ref(0)
const securityQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  type: '',
  ip: '',
  timeRange: []
})

// 详情对话框相关
const detailDialogVisible = ref(false)
const detailDialogTitle = ref('')
const currentDetail = ref({})

// 处理对话框相关
const processDialogVisible = ref(false)
const processFormRef = ref(null)
const processForm = reactive({
  id: '',
  action: '',
  remark: ''
})
const processRules = {
  action: [
    { required: true, message: '请选择处理方式', trigger: 'change' }
  ],
  remark: [
    { required: true, message: '请输入处理说明', trigger: 'blur' }
  ]
}

// 初始化
onMounted(() => {
  loadOperationLogs()
  loadSystemLogs()
  loadSecurityLogs()
})

// 加载操作日志
const loadOperationLogs = async () => {
  operationLoading.value = true
  try {
    const params = {
      ...operationQuery,
      startTime: operationQuery.timeRange?.[0],
      endTime: operationQuery.timeRange?.[1]
    }
    const res = await getOperationLogs(params)
    operationLogs.value = res.data.list
    operationTotal.value = res.data.total
  } catch (error) {
    console.error('加载操作日志失败:', error)
    ElMessage.error('加载操作日志失败')
  } finally {
    operationLoading.value = false
  }
}

// 加载系统日志
const loadSystemLogs = async () => {
  systemLoading.value = true
  try {
    const params = {
      ...systemQuery,
      startTime: systemQuery.timeRange?.[0],
      endTime: systemQuery.timeRange?.[1]
    }
    const res = await getSystemLogs(params)
    systemLogs.value = res.data.list
    systemTotal.value = res.data.total
  } catch (error) {
    console.error('加载系统日志失败:', error)
    ElMessage.error('加载系统日志失败')
  } finally {
    systemLoading.value = false
  }
}

// 加载安全日志
const loadSecurityLogs = async () => {
  securityLoading.value = true
  try {
    const params = {
      ...securityQuery,
      startTime: securityQuery.timeRange?.[0],
      endTime: securityQuery.timeRange?.[1]
    }
    const res = await getSecurityLogs(params)
    securityLogs.value = res.data.list
    securityTotal.value = res.data.total
  } catch (error) {
    console.error('加载安全日志失败:', error)
    ElMessage.error('加载安全日志失败')
  } finally {
    securityLoading.value = false
  }
}

// 查询操作日志
const handleQueryOperationLog = () => {
  operationQuery.pageNum = 1
  loadOperationLogs()
}

// 查询系统日志
const handleQuerySystemLog = () => {
  systemQuery.pageNum = 1
  loadSystemLogs()
}

// 查询安全日志
const handleQuerySecurityLog = () => {
  securityQuery.pageNum = 1
  loadSecurityLogs()
}

// 重置操作日志查询
const handleResetOperationQuery = () => {
  Object.assign(operationQuery, {
    pageNum: 1,
    pageSize: 10,
    type: '',
    operator: '',
    timeRange: []
  })
  loadOperationLogs()
}

// 重置系统日志查询
const handleResetSystemQuery = () => {
  Object.assign(systemQuery, {
    pageNum: 1,
    pageSize: 10,
    level: '',
    module: '',
    timeRange: []
  })
  loadSystemLogs()
}

// 重置安全日志查询
const handleResetSecurityQuery = () => {
  Object.assign(securityQuery, {
    pageNum: 1,
    pageSize: 10,
    type: '',
    ip: '',
    timeRange: []
  })
  loadSecurityLogs()
}

// 导出操作日志
const handleExportOperationLog = async () => {
  try {
    const params = {
      ...operationQuery,
      startTime: operationQuery.timeRange?.[0],
      endTime: operationQuery.timeRange?.[1]
    }
    await exportOperationLogs(params)
    ElMessage.success('导出操作日志成功')
  } catch (error) {
    console.error('导出操作日志失败:', error)
    ElMessage.error('导出操作日志失败')
  }
}

// 导出系统日志
const handleExportSystemLog = async () => {
  try {
    const params = {
      ...systemQuery,
      startTime: systemQuery.timeRange?.[0],
      endTime: systemQuery.timeRange?.[1]
    }
    await exportSystemLogs(params)
    ElMessage.success('导出系统日志成功')
  } catch (error) {
    console.error('导出系统日志失败:', error)
    ElMessage.error('导出系统日志失败')
  }
}

// 导出安全日志
const handleExportSecurityLog = async () => {
  try {
    const params = {
      ...securityQuery,
      startTime: securityQuery.timeRange?.[0],
      endTime: securityQuery.timeRange?.[1]
    }
    await exportSecurityLogs(params)
    ElMessage.success('导出安全日志成功')
  } catch (error) {
    console.error('导出安全日志失败:', error)
    ElMessage.error('导出安全日志失败')
  }
}

// 查看操作日志详情
const handleViewOperationDetail = (row) => {
  currentDetail.value = row
  detailDialogTitle.value = '操作日志详情'
  detailDialogVisible.value = true
}

// 查看系统日志详情
const handleViewSystemDetail = (row) => {
  currentDetail.value = row
  detailDialogTitle.value = '系统日志详情'
  detailDialogVisible.value = true
}

// 查看安全日志详情
const handleViewSecurityDetail = (row) => {
  currentDetail.value = row
  detailDialogTitle.value = '安全日志详情'
  detailDialogVisible.value = true
}

// 处理安全事件
const handleProcessSecurityEvent = (row) => {
  processForm.id = row.id
  processForm.action = ''
  processForm.remark = ''
  processDialogVisible.value = true
}

// 提交安全事件处理
const handleSubmitProcess = async () => {
  if (!processFormRef.value) return
  
  try {
    await processFormRef.value.validate()
    await processSecurityEvent(processForm)
    ElMessage.success('处理安全事件成功')
    processDialogVisible.value = false
    loadSecurityLogs()
  } catch (error) {
    console.error('处理安全事件失败:', error)
    ElMessage.error('处理安全事件失败')
  }
}

// 分页相关方法
const handleOperationSizeChange = (val) => {
  operationQuery.pageSize = val
  loadOperationLogs()
}

const handleOperationCurrentChange = (val) => {
  operationQuery.pageNum = val
  loadOperationLogs()
}

const handleSystemSizeChange = (val) => {
  systemQuery.pageSize = val
  loadSystemLogs()
}

const handleSystemCurrentChange = (val) => {
  systemQuery.pageNum = val
  loadSystemLogs()
}

const handleSecuritySizeChange = (val) => {
  securityQuery.pageSize = val
  loadSecurityLogs()
}

const handleSecurityCurrentChange = (val) => {
  securityQuery.pageNum = val
  loadSecurityLogs()
}

// 工具方法
const getOperationTypeTag = (type) => {
  const map = {
    login: 'success',
    create: 'primary',
    update: 'warning',
    delete: 'danger',
    export: 'info',
    other: ''
  }
  return map[type] || ''
}

const getOperationTypeLabel = (type) => {
  const map = {
    login: '登录',
    create: '新增',
    update: '修改',
    delete: '删除',
    export: '导出',
    other: '其他'
  }
  return map[type] || type
}

const getLogLevelTag = (level) => {
  const map = {
    info: 'info',
    warn: 'warning',
    error: 'danger',
    debug: ''
  }
  return map[level.toLowerCase()] || ''
}

const getSecurityTypeTag = (type) => {
  const map = {
    login_error: 'danger',
    password_error: 'warning',
    unauthorized: 'error',
    sensitive: 'warning',
    other: 'info'
  }
  return map[type] || ''
}

const getSecurityTypeLabel = (type) => {
  const map = {
    login_error: '登录异常',
    password_error: '密码错误',
    unauthorized: '越权访问',
    sensitive: '敏感操作',
    other: '其他'
  }
  return map[type] || type
}

const getSecurityStatusTag = (status) => {
  const map = {
    pending: 'warning',
    processing: 'info',
    resolved: 'success',
    ignored: ''
  }
  return map[status] || ''
}

const getSecurityStatusLabel = (status) => {
  const map = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已解决',
    ignored: '已忽略'
  }
  return map[status] || status
}

const getDetailLabel = (key) => {
  const map = {
    type: '操作类型',
    operator: '操作人',
    module: '操作模块',
    content: '操作内容',
    ip: 'IP地址',
    location: '操作地点',
    status: '状态',
    createTime: '操作时间',
    level: '日志级别',
    stackTrace: '堆栈信息',
    remark: '备注'
  }
  return map[key] || key
}
</script>

<style lang="scss" scoped>
.monitor-log {
  padding: 20px;
  
  .log-header {
    margin-bottom: 20px;
    
    .query-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style> 